/*
 * @Author: RYPY
 * @Date: 2021-03-20 14:52:05
 * @LastEditors: RYPY
 * @LastEditTime: 2021-03-20 19:05:03
 */
const express=require("express");
const DB=require("../until/DB")
const {Msg,serverPath,checkToken}=require("../until/config");
const router=express.Router();

//视频播放接口
router.get("/videoplay/:id",async(req,res,next)=>{
   let {id}=req.params;
   let sql=`select concat("${serverPath}/course_video/",video_src) as video_src,video_title from e_video where id='${id}'`;
   let [err,result]=await DB.query(sql);
   if(!err){
       res.send(Msg(200,"ok",result));
   }else{
       next("请稍后再试！");
   } 
});

//课程学习
router.post("/study",async(req,res,next)=>{
    let {cid}=req.body;
    let {uid}=checkToken(req.header.authorization);
    //订单必须是日期时间+随机8位数
    let date=new Date();
    let oid=date.toLocaleDateString().replaceAll("/","")+date.toLocaleTimeString().replaceAll(":","").substring(2)+(Math.random()+"").substring(2,10);
    //查询该用户是否购买过该课程
    let sql=`select count(id) n from e_order where cid='${cid}' and mid='${uid}'`;
    let [err,result]=await DB.query(sql);
    if(!err){
        if(result[0].n>0){
            res.send(Msg(201,"该课程已经购买过"));
        }
    }else{
        next("请稍后再试");
    }
    sql=`insert e_order(oid,cid,mid,createdate,status) value("${oid}","${cid}","${uid}","${date}",1)`;
    [err,result]=await DB.query(sql);
    if(!err){
        res.send(Msg(200,"ok"));
    }else{
        next("请稍后再试");
    }
});
//用户课程订单
router.get("/orders",async(req,res,next)=>{
   let{uid}=checkToken(req.headers.authorization);
   if(uid===""){
       next("用户ID无效，请登录！");
   }
   let sql=`SELECT oid,title,price,c.intro,realname,head_photo_url from e_order o LEFT JOIN e_course  c ON o.cid=c.cid LEFT JOIN e_teacher t ON c.tid=t.tid WHERE mid='${uid}' ORDER BY createdate DESC`;
   let [err,result]=await DB.query(sql);
   if(!err){
       res.send(Msg(200,"ok",result));
   } else{
       next("请稍后再试！");
   }
});

module.exports=router;